package it.tukano.swingdeco.input;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import javax.swing.JPanel;

public class ColorBox extends JPanel {

    /* Serial version of this class */
    private static final long serialVersionUID = 0;

    private final Rectangle dot = new Rectangle(0, 0, 16, 16);

    /**
     * Instance initializer
     */
    public ColorBox(int preferredWidth, int preferredHeight) {
        setPreferredSize(new Dimension(preferredWidth, preferredHeight));
    }

    @Override
    public void setForeground(Color fg) {
        super.setForeground(fg);
        repaint();
    }

    @Override
    protected void paintComponent(Graphics graphics) {
        dot.width = Math.max(5, getWidth() / 10);
        dot.height = dot.width;
        super.paintComponent(graphics);
        Graphics2D g = (Graphics2D) graphics;
        int w = getWidth();
        int h = getHeight();
        int dotSize = dot.width;
        int colCount = 1 + w / dotSize;
        if (colCount % 2 == 0) {
            colCount += 1;
        }
        int rowCount = 1 + h / dotSize;
        int dotCount = colCount * rowCount;
        for (int i = 0; i < dotCount; i++) {
            int row = i / colCount;
            int col = i % colCount;
            dot.setLocation(col * dotSize, row * dotSize);
            g.setPaint(i % 2 == 0 ? Color.GRAY : Color.WHITE);
            g.fill(dot);
        }
        g.setPaint(getForeground());
        g.fillRect(0, 0, w, h);
    }
}
